<template page>
  <l-m src="/packages/pui/progress/progress.html"></l-m>
  <style>
    :host {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      height: 100%;
    }

    h1 {
      font-size: 24px;
    }
  </style>
  <n-local-icon
    name="succeed"
    style="color: var(--md-sys-color-success); font-size: 60px"
  ></n-local-icon>
  <h1>
    <n-desc name="installSucceed" space="installer"></n-desc>
  </h1>
  <o-if :value="redirectPath">
    <div style="display: flex">
      <p-button style="margin: 4px">
        <a attr:href="redirectPath">
          <localized-content>
            <span lang="cn">进入应用{{appName}}</span>
            <span lang="en">Enter App {{appName}}</span>
            <span lang="ja">アプリを開く {{appName}}</span>
          </localized-content>
        </a>
      </p-button>

      <p-button variant="outlined" style="margin: 4px">
        <a href="/">
          <n-desc name="entrySystem" space="installer"></n-desc>
        </a>
      </p-button>
    </div>
  </o-if>
  <o-else>
    <p-button>
      <a href="/">
        <n-desc name="entrySystem" space="installer"></n-desc>
      </a>
    </p-button>
  </o-else>
  <script>
    export default async ({ load }) => {
      return {
        data: {
          files: [],
          redirectPath: "",
          appName: "",
        },
        attached() {
          if (window.__useOnlinePkgTimer) {
            // 转换为本地包
            clearInterval(window.__useOnlinePkgTimer);
            fetch("/package-use-local");

            // 判断本地是否有注册 service worker，有的话进行更新
            if ("serviceWorker" in navigator) {
              navigator.serviceWorker
                .getRegistrations()
                .then((registrations) => {
                  return Promise.all(
                    registrations.map((registration) => {
                      return registration.update();
                    })
                  );
                })
                .then(() => {
                  // 注销成功
                  console.log("Service worker updated");
                });
            }
            // import("/sw/register.js");
          }

          const redirectPath = new URLSearchParams(location.search).get(
            "redirect"
          );
          if (redirectPath) {
            this.redirectPath = decodeURIComponent(redirectPath);
          }

          load("/sw/register.js");

          if (this.redirectPath) {
            (async () => {
              // 尝试获取应用名
              const appData = await fetch(this.redirectPath + "/app.json").then(
                (e) => e.json()
              );

              this.appName = appData.name;
            })();
          }
        },
      };
    };
  </script>
</template>
